/**
 * 1. 这里学会了通过eslint的配置文件，来配置tsx文件的校验规则
 * 2. const { confirmPassword: _confirmPassword, ...userData } = values; _confirmPassword表示忽略掉confirmPassword字段，其余的都放到userData中
 */
import { Modal, Form, Input, Select, Button, message } from "antd";
import { useEffect } from "react";

// 定义用户类型用接口
interface User {
    id: number;
    username: string;
    password: string;
    email: string;
    phone?: string;
    nickname?: string;
    avatar?: string;
    status?: boolean;
    role?: string;
}

// 定义组件的props类型用接口
interface UserEditModalProps {
    visible: boolean;
    user: User | undefined;
    onCancel: () => void;
    onSave: (user: User) => void;
    loading?: boolean;
}

export default function UserEditModal({ visible, user, onCancel, onSave, loading }: UserEditModalProps) {
    // 创建一个表单实例，用于表单的校验和获取值
    const [form] = Form.useForm();

    // 组件挂载后，如果visible为true且user不为空，则将表单的值设置为user的值；否则重置表单字段
    // 监听visible和user的变化，当visible为true且user不为空时，将表单的值设置为user的值；否则重置表单字段
    useEffect(() => {
        if (visible && user) {
            form.setFieldsValue(user);
        } else {
            form.resetFields();
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [visible, user]);

    const handleSave = async () => {
        try {
            const values = await form.validateFields();
            // 新增用户时移除确认密码字段
            const { confirmPassword: _confirmPassword, ...userData } = values;
            // 保存用户数据，如果用户已存在则更新，否则新增
            onSave({ ...user, ...userData });
        } catch {
            message.error("表单验证失败");
        }
    };

    return (
        // 这里使用了Modal组件，并通过props传递了title、open、onCancel等属性
        <Modal
            title={ user ? "编辑用户" : "新增用户" }
            open={ visible }
            onCancel={ onCancel }
            footer={[
                <Button key="cancel" onClick={ onCancel }>
                    取消
                </Button>,
                <Button key="save" type="primary" loading={ loading } onClick={ handleSave }>
                    保存
                </Button>,
            ]}
            width={600}
            destroyOnHidden
        >
            <Form
                form={ form }
                layout="vertical" // 垂直布局
                initialValues={{ // 设置表单的初始值
                    status: true,
                    role: "user"
                }}
                preserve={ false } // 保存表单数据到Form实例中
            >
                {!user?.id && (
                    // React.Fragment(片段)的简写形式，即<></> 不用引入额外DOM元素，提高渲染效率
                    <>
                        <Form.Item
                            name="password"
                            label="密码"
                            rules={[{ required: !user?.id, message: "请输入密码" }]}
                        >
                            <Input.Password placeholder="请输入密码" />
                        </Form.Item>
                        <Form.Item
                            name="confirmPassword"
                            label="确认密码"
                            dependencies={['password']}
                            rules={[
                                { required: !user?.id, message: "请确认密码" },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('password') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('两次输入的密码不一致'));
                                    },
                                }),
                            ]}
                        >
                            <Input.Password placeholder="请再次输入密码" />
                        </Form.Item>
                    </>
                )}

                <Form.Item
                    name="username"
                    label="用户名"
                    rules={[{ required: true, message: "请输入用户名" }]}
                >
                    <Input placeholder="请输入用户名" />
                </Form.Item>

                <Form.Item
                    name="nickname"
                    label="昵称"
                >
                    <Input placeholder="请输入昵称" />
                </Form.Item>

                <Form.Item
                    name="email"
                    label="邮箱"
                    rules={[
                        { required: true, message: "请输入邮箱" },
                        { type: "email", message: "请输入有效的邮箱地址" }
                    ]}
                >
                    <Input placeholder="请输入邮箱" />
                </Form.Item>

                <Form.Item
                    name="phone"
                    label="手机号"
                    rules={[{ required: !user?.id, message: "请输入手机号" }]}
                >
                    <Input placeholder="请输入手机号" />
                </Form.Item>

                <Form.Item
                    name="status"
                    label="状态"
                    rules={[{ required: true, message: "请选择状态" }]}
                >
                    <Select>
                        <Select.Option value={true}>正常</Select.Option>
                        <Select.Option value={false}>禁用</Select.Option>
                    </Select>
                </Form.Item>

                <Form.Item
                    name="role"
                    label="角色"
                    rules={[{ required: true, message: "请选择角色" }]}
                >
                    <Select>
                        <Select.Option value="user">普通用户</Select.Option>
                        <Select.Option value="admin">管理员</Select.Option>
                    </Select>
                </Form.Item>

                <Form.Item
                    name="avatar"
                    label="头像URL"
                >
                    <Input placeholder="请输入头像URL" />
                </Form.Item>
            </Form>
        </Modal>
    );
}